package be.nvlooy.moviereminder.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import be.nvlooy.moviereminder.entities.User;
import be.nvlooy.moviereminder.service.UserService;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
	
	private UserService userService;
	
	private Assembler assembler;
	
	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Autowired
	public void setAssembler(Assembler assembler) {
		this.assembler = assembler;
	}

	@Transactional(readOnly = true)
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		
		User user = userService.findByUserName(username);

		if (user == null)
			throw new UsernameNotFoundException("user with username: " + username + " not found");

		return assembler.buildUserFromUserEntity(user);
	}
}
